<?php
/* SVN FILE: $Id: calendars_controller.php 250 2010-06-17 10:55:41Z gregory.rome $ */
/**
 * Calendars Controller.
 *
 * The calendars controller provides function to add, import, edit and compute
 * ranking.
 *
 * cBBweb : Digital Blood Bowl league interface (http://code.google.com/p/cbbweb/)
 * Copyright 2009-2010, Grégory Romé.
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2009-2010, Grégory Romé.
 * @link          http://code.google.com/p/cbbweb/ cBBweb Project
 * @package       cbbweb
 * @subpackage    cbbweb.controllers
 * @version       $Revision: 250 $
 * @modifiedby    $LastChangedBy: gregory.rome $
 * @lastmodified  $Date: 2010-06-17 10:55:41 +0000 (Thu, 17 Jun 2010) $
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */
/**
 * Calendars Controller.
 *
 * @package       cbbweb
 * @subpackage    cbbweb.controllers
 */
class CalendarsController extends AppController {
	var $name = 'Calendars';
	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function index() {
		if (!$this->championship) {
			$this->Session->setFlash(__('You must select a championship', true));
			$this->set('noview', true);
			return;
		} else {
			$this->set('noview', false);
			App :: import('Model', 'Championship');
			$Championship = new Championship();
			$championship = $Championship->read(null, $this->championship);

			App :: import('Model', 'ChampionshipHasCalendar');
			$ChampionshipHasCalendar = new ChampionshipHasCalendar();
			$calendar_list = $ChampionshipHasCalendar->find('list', array (
				'fields' => array ('idCalendar'),
				'conditions' => array ('idChampionship' => $this->championship)
			));
		}
		$ctype = $championship['Championship']['idRule_Types'];
		$nbTeams = $championship['Championship']['iNbTeams'];
		switch ($ctype) {
			case 1 /*Championship*/:
				$numGroups = $championship['Championship']['Championship_iNbGroups'];
				$numDays = $championship['Championship']['Championship_iNbMatchsPerGroup'];
				$calendars = array ();
				for ($day = $numDays; $day > 0; $day--) {
					for ($group = $numGroups; $group > 0; $group--) {
						$calendars[$day][$group] = $this->Calendar->find('all', array (
							'conditions' => array (
								'Calendar.Championship_iGroup' => $group,
								'Calendar.Championship_iDay' => $day,
								'Calendar.ID' => $calendar_list
							)
						));
					}
				}
				break;
			case 2 : /*Cup*/
				$numGroups = $championship['Championship']['Cup_iNbGroups'];
				$numDays = $championship['Championship']['Cup_iNbMatchsPerGroup'];
				break;
			case 3 : /*GrandChelem*/
				break;
			case 4 : /*Playoff*/
				$numGroups = $championship['Championship']['Cup_iNbGroups'];
				$numDays = $championship['Championship']['Cup_iNbMatchsPerGroup'];
				$calendars = array ();
				for ($day = $numDays; $day > 0; $day--) {
					$calendars[$day] = $this->Calendar->find('all', array (
						'fields' => array (
							'Calendar.idTeam_Listing_Away',
							'Calendar.idTeam_Listing_Home',
							'Calendar.Championship_iDay',
							'Calendar.Playoff_iEliminationLevel',
							'Calendar.Away_iScore',
							'Calendar.Home_iScore',

						),
						'contain' => array (
							'TeamHome' => array (
								'fields' => array ('TeamHome.strName')
							),
							'TeamAway' => array (
								'fields' => array ('TeamAway.strName')
							)
						),
						'conditions' => array (
							'Championship_iDay' => $day,
							'Calendar.ID' => $calendar_list
						),
						'order' => array ('Calendar.Championship_iGroup' => 'asc')
					));
				}
				break;
		}
		$this->set('calendars', $calendars);
		$this->set('numDays', $numDays);
		$this->set('numGroups', $numGroups);
		$this->set('nbTeams', $nbTeams);
		$this->set('ctype', $ctype);
	}
	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Calendar.', true));
			$this->redirect(array (
				'action' => 'index'
			));
		}
		$this->set('calendar', $this->Calendar->read(null, $id));
	}
	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function add() {
		if (!empty ($this->data['Calendar'])) {
			if (isset ($this->params['form']['button']) && $this->params['form']['button'] == 'Submit') {
				$this->Calendar->create();
				if ($this->Calendar->save($this->data)) {
					$this->Session->setFlash(__('The Calendar has been saved', true));
					$this->redirect(array (
						'action' => 'index'
					));
				} else {
					$this->Session->setFlash(__('The Calendar could not be saved. Please, try again.', true));
				}
			}
		}
	}
	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function edit($id = null) {
		if (!$id && empty ($this->data)) {
			$this->Session->setFlash(__('Invalid Calendar', true));
			$this->redirect(array (
				'action' => 'index'
			));
		}
		if (!empty ($this->data)) {
			if ($this->Calendar->save($this->data)) {
				$this->Session->setFlash(__('The Calendar has been saved', true));
				$this->redirect(array (
					'action' => 'index'
				));
			} else {
				$this->Session->setFlash(__('The Calendar could not be saved. Please, try again.', true));
			}
		}
		if (empty ($this->data)) {
			$this->data = $this->Calendar->read(null, $id);
		}
	}
	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Calendar', true));
			$this->redirect(array (
				'action' => 'index'
			));
		}
		if ($this->Calendar->del($id)) {
			$this->Session->setFlash(__('Calendar deleted', true));
			$this->redirect(array (
				'action' => 'index'
			));
		}
	}
	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function upload() {
		if (!$this->championship) {
			$this->Session->setFlash(__('You must select a championship', true));
			$this->set('noform', true);
			return;
		} else {
			$this->set('noform', false);
			App :: import('Model', 'ChampionshipHasCalendar');
			$ChampionshipHasCalendar = new ChampionshipHasCalendar();
			$calendar_list = $ChampionshipHasCalendar->find('list', array (
				'fields' => array ('idCalendar'),
				'conditions' => array ('idChampionship' => $this->championship)
			));

			App :: import('Model', 'ChampionshipHasTeam');
			$ChampionshipHasTeam = new ChampionshipHasTeam();
		}

		if (!empty ($this->data['Calendar'])) {
			$file = $this->data['Calendar']['MatchReport'];
			if (!$this->isUploadedFile($file)) {
				$this->Session->setFlash(__('Upload failed', true));
			} else {
				rename($file['tmp_name'], '/tmp/last_report.sqlite');
				/* ---------------------------------------------------------- */
				$this->Calendar->changeDataSource('sqlite');
				$this->Calendar->recursive = 0;
				$calendar = $this->Calendar->find('first');
				$this->Calendar->changeDataSource('default');

				/* Check if the teams are corrects */
				$result = $ChampionshipHasTeam->find('list', array (
					'fields' => array ('idTeam'),
					'conditions' => array (
						'idChampionship' => $this->championship,
						'idTeam' => $calendar['Calendar']['idTeam_Listing_Away'])
				));

				if(!$result) {
					$this->Session->setFlash(__('Invalid Team', true));
					return;
				}

				$result = $ChampionshipHasTeam->find('list', array (
					'fields' => array ('idTeam'),
					'conditions' => array (
						'idChampionship' => $this->championship,
						'idTeam' => $calendar['Calendar']['idTeam_Listing_Home'],)
				));

				if(!$result) {
					$this->Session->setFlash(__('Invalid Team', true));
					return;
				}

				/* ---------------------------------------------------------- */
				/* Search the ID of the calendar if it exists */
				$result = $this->Calendar->find('first', array (
					'fields' => array ('Calendar.ID', 'Calendar.bPlayed'),
					'conditions' => array (
						'idTeam_Listing_Away' => $calendar['Calendar']['idTeam_Listing_Away'],
						'idTeam_Listing_Home' => $calendar['Calendar']['idTeam_Listing_Home'],
						'Championship_iDay' => $calendar['Calendar']['Championship_iDay'],
						'Championship_iSeason' => $calendar['Calendar']['Championship_iSeason'])
				));

				if ($result) {
					if( $result['Calendar']['bPlayed'] == 1 ) {
						$this->Session->setFlash(__('Match already played', true));
						return;
					}

					$calendar['Calendar']['ID'] = $result['Calendar']['ID'];

					unset($result);
				} else {
					unset ($calendar['Calendar']['ID']);
					$this->Calendar->create();
				}
				$calendar['Calendar']['bPlayed'] = 1;

				/* ---------------------------------------------------------- */
				$this->Calendar->TeamHome->Player->changeDataSource('sqlite', 'home_player_listing');
				$this->Calendar->TeamHome->Player->StatisticsPlayer->changeDataSource('sqlite', 'home_statistics_players');
				$this->Calendar->TeamHome->Player->recursive = 1;
				$teamHomePlayers = $this->Calendar->TeamHome->Player->find('all');
				$this->Calendar->TeamHome->Player->changeDataSource('default', 'player_listing');
				$this->Calendar->TeamHome->Player->StatisticsPlayer->changeDataSource('default', 'statistics_players');


				foreach ($teamHomePlayers as $teamHomePlayer) {
					if (!$teamHomePlayer['Player']['bGenerated']) {
						$player = $this->Calendar->TeamHome->Player->find('first', array (
							'conditions' => array (
								'Player.ID' => $teamHomePlayer['Player']['ID'])
						));

						/* Create player if it does not exist */
						if(!$player) {
							unset($teamHomePlayer['Player']['ID']);
							unset($teamHomePlayer['StatisticsPlayer']['ID']);
							$this->Calendar->TeamHome->Player->create();
						} else {
							$result = $this->Calendar->TeamHome->Player->StatisticsPlayer->find('first', array(
								'fields' => array('StatisticsPlayer.ID'),
								'conditions' => array('StatisticsPlayer.idPlayer_Listing' => $teamHomePlayer['Player']['ID'])
							));

							if(!$result) {
								unset($teamHomePlayer['StatisticsPlayer']['ID']);
							} else {
								$teamHomePlayer['StatisticsPlayer']['ID'] = $result['StatisticsPlayer']['ID'];
								unset($result);
							}

						}

						unset($teamHomePlayer['Team']);
						unset($teamHomePlayer['PlayerType']);
						unset($teamHomePlayer['Race']);
						unset($teamHomePlayer['PlayerLevel']);
						unset($teamHomePlayer['PlayerSeasonStatistic']);
						unset($teamHomePlayer['Skill']);

						$this->Calendar->TeamHome->Player->saveAll($teamHomePlayer);
					}
				}

				/* ---------------------------------------------------------- */
				$this->Calendar->TeamAway->Player->changeDataSource('sqlite', 'away_player_listing');
				$this->Calendar->TeamAway->Player->StatisticsPlayer->changeDataSource('sqlite', 'away_statistics_players');
				$this->Calendar->TeamAway->Player->recursive = 1;
				$teamAwayPlayers = $this->Calendar->TeamAway->Player->find('all');
				$this->Calendar->TeamAway->Player->changeDataSource('default', 'player_listing');
				$this->Calendar->TeamAway->Player->StatisticsPlayer->changeDataSource('default', 'statistics_players');

				foreach ($teamAwayPlayers as $teamAwayPlayer) {
					if (!$teamAwayPlayer['Player']['bGenerated']) {
						$player = $this->Calendar->TeamAway->Player->find('first', array (
							'conditions' => array (
								'Player.ID' => $teamAwayPlayer['Player']['ID'])
						));

						/* Create player if it does not exist */
						if(!$player) {
							unset($teamAwayPlayer['Player']['ID']);
							unset($teamAwayPlayer['StatisticsPlayer']['ID']);
							$this->Calendar->TeamAway->Player->create();
						} else {
							$result = $this->Calendar->TeamAway->Player->StatisticsPlayer->find('first', array(
								'fields' => array('StatisticsPlayer.ID'),
								'conditions' => array('StatisticsPlayer.idPlayer_Listing' => $teamHomePlayer['Player']['ID'])
							));

							if(!$result) {
								unset($teamAwayPlayer['StatisticsPlayer']['ID']);
							} else {
								$teamAwayPlayer['StatisticsPlayer']['ID'] = $result['StatisticsPlayer']['ID'];
								unset($result);
							}

						}

						unset($teamAwayPlayer['Team']);
						unset($teamAwayPlayer['PlayerType']);
						unset($teamAwayPlayer['Race']);
						unset($teamAwayPlayer['PlayerLevel']);
						unset($teamAwayPlayer['PlayerSeasonStatistic']);
						unset($teamAwayPlayer['Skill']);

						$this->Calendar->TeamAway->Player->saveAll($teamAwayPlayer);
					}
				}

				unset ($calendar['TeamAway']);
				unset ($calendar['TeamHome']);

				$this->Calendar->save($calendar);

				App :: import('Model', 'Championship');
				$Championship = new Championship();
				$Championship->recursive = -1;
				$championship = $Championship->read(null, $this->championship);
				$championship['Calendar'][] = $this->Calendar->getId();
				$Championship->save($championship);

				$this->Session->setFlash(__('Calendar imported', true));
				$this->redirect(array ('action' => 'index'));
			}
		}
	}
}
?>
